//
//  FileManager+Extension.swift
//  RemoteService
//
//  Created by Longxiang Guo (QXQ4633) on 2021/5/27.
//

import Foundation


import Foundation

public enum FileManagerError: Error {
    case unableToCalculateRemainingFreeSpace
    case documentsDirectoryNotFound
}

public protocol FileManagerProtocol {
    func urls(for directory: FileManager.SearchPathDirectory, in domainMask: FileManager.SearchPathDomainMask) -> [URL]
    func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions) throws -> [URL]
    func contentsOfDirectory(atPath path: String) throws -> [String]
    func fileExists(atPath path: String) -> Bool
    func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool
    func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey: Any]?) throws
    func removeItem(atPath path: String) throws
    func removeItem(at URL: URL) throws
    func moveItem(at srcURL: URL, to dstURL: URL) throws
    func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey: Any]?) -> Bool
    func contents(atPath path: String) -> Data?

    func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey: Any]
    func attributesOfItem(atPath path: String) throws -> [FileAttributeKey: Any]
    func deviceRemainingFreeSpaceInBytes() throws -> Int
    func documentsDirectory() throws -> URL
    func enumerator(atPath path: String) -> FileManager.DirectoryEnumerator?
}

extension FileManagerProtocol {

    public func deviceRemainingFreeSpaceInBytes() throws -> Int {
        let directory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
        guard let documentDirectory = directory,
              let systemAttributes = try? attributesOfFileSystem(forPath: documentDirectory),
              let freeSize = systemAttributes[.systemFreeSize] as? NSNumber else {
                throw FileManagerError.unableToCalculateRemainingFreeSpace
        }

        return freeSize.intValue
    }

    public func documentsDirectory() throws -> URL {
        guard let documentsDirectory = urls(for: .documentDirectory, in: .userDomainMask).first else {
            throw FileManagerError.documentsDirectoryNotFound
        }
        return documentsDirectory
    }
}

extension FileManager: FileManagerProtocol {
}
